package com.controller;

import com.po.Book;
import com.service.BookService;
import com.vo.Code;
import com.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    //查询所有图书
    @GetMapping
    public Result findAll() {
        List<Book> books = bookService.findAll();
        Integer code = books != null ? Code.SELECT_OK : Code.SELECT_ERROR;
        String msg = books != null ? "查询成功" : "查询失败";
        return new Result(code, msg, books);
    }

    //根据Id查询图书
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        Book book = bookService.findById(id);
        Integer code = book != null ? Code.SELECT_OK : Code.SELECT_ERROR;
        String msg = book != null ? "查询成功" : "查询失败";
        return new Result(code, msg, book);
    }


    //添加图书
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean save = bookService.save(book);
        Integer code = save == true ? Code.SAVE_OK : Code.SAVE_ERROR;
        String msg = save == true ? "添加成功" : "添加失败";
        return new Result(code, msg, save);
    }

    //编辑图书
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean update = bookService.update(book);
        Integer code = update == true ? Code.UPDATE_OK : Code.UPDATE_ERROR;
        String msg = update == true ? "修改成功" : "修改失败";
        return new Result(code, msg, update);
    }

    //删除图书
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean delete = bookService.delete(id);
        Integer code = delete == true ? Code.DELETE_OK : Code.DELETE_ERROR;
        String msg = delete == true ? "删除成功" : "删除失败";
        return new Result(code, msg, delete);
    }
}
